const Koa = require('koa');
const static = require('koa-static');
const router = require('koa-router')();
const bodyparser = require('koa-bodyparser');
const path = require('path');
let query = require('./db/index');
let app = new Koa();
//__dirname  process.cwd()
//处理静态资源
app.use(static(path.join(__dirname,'public')));
app.use(bodyparser());
app.use(router.routes())
app.use(router.allowedMethods())
// router.get(url,)   ctx.query
router.get('/api/userlist',async (ctx) => {
    try{  //尝试执行
        let list = await query('select * from qqlistx');  //从数据库里查询数据是异步的操作
        ctx.body = {
            code:1,
            data:list
        }    
    }catch(e){
        ctx.body = {
            code:0,
            msg:e
        }
    }   
})
router.post('/api/add',async (ctx) => {
    let {username,password,phone} = ctx.request.body; 
    //查此人是否存在
    if(username && password){
        let user = await query('select * from qqlistx where username=?',[username]);
        if(user.length){
            //此人已存在
            ctx.body = {
                code:2,
                msg:'此用户名已被注册，请换一个'
            }
        }else{
             //插入数据
            try{
                await query('insert into qqlistx (username,password,phone) values (?,?,?)',[username,password,phone])
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺失参数'
        }
    }  
})

router.get('/api/del',async (ctx) => {
    let {id} = ctx.query;
    if(id){  //容错处理
        await query('delete from qqlistx where id=?',[id]);
        ctx.body ={
            code:1,
            msg:'删除成功'
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺失参数'
        }
    }
})

app.listen(3000,() => {
    console.log("服务器启动成功")
})